import {createApi} from "@/soar/utils/request";
import {mockResponse, nextId, randomElement, randomNumber, randomString} from "@/soar/utils/random";
import {isTrue, notEmpty} from "@/soar/utils/assert";


const api = createApi<any>('demo', 'demo');

export const sex = {
    0: '未知',
    1: '男',
    2: '女',
}

const list: any[] = [];
for (let i = 0; i < 57; i++) {
    list.push({
        id: nextId(),
        name: randomString(5),
        age: randomNumber(18, 60),
        sex: randomElement(Object.keys(sex)),
    })
}

export default {
    ...api,
    query(params: any) {
        const total = list.length;
        const start = (params.pageNo - 1) * params.pageSize;
        const end = (params.pageNo * params.pageSize) > total ? total : params.pageNo * params.pageSize;
        return mockResponse(
            { data: { list: list.slice(start, end), total } },
            { msg: '操作失败' }
        )
    },
    create(data: any) {
        list.push({ ...data, id: nextId(), })
        return mockResponse(undefined, { msg: '操作失败' })
    },
    update(data: any) {
        const i = list.findIndex(x => x.id === data.id);
        isTrue(i !== -1, '数据不存在')
        list[i] = {...list[i], ...data};
        return mockResponse(undefined, { msg: '操作失败' })
    },
    detail(id: number) {
        const d = list.find(x => x.id == id);
        notEmpty(d, '数据不存在')
        return mockResponse({ data: d }, { msg: '操作失败' })
    },
    remove(id: number) {
        const i = list.findIndex(x => x.id === id);
        if (i !== -1) {
            list.splice(i, 1)
        }
        return mockResponse(undefined, { msg: '操作失败' })
    }
}